import { request } from "../../request/index.js";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    goodsObj: {},
    isCollect: false, //商品是否被收藏
  },

  //全局变量 商品对象
  GoodsInfo: {},

  /**
   * 生命周期函数--监听页面加载
   */
  onShow: function () {
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1];
    let options = currentPage.options;
    const { goods_id } = options;
    this.getGoodsDetail(goods_id);
  },

  //获取商品的详情数据
  async getGoodsDetail(goods_id) {
    const res = await request({ url: "/goods/detail", data: { goods_id } });
    this.GoodsInfo = res;
    console.log(res);
    //1获取缓存中商品收藏数组
    let collect = wx.getStorageSync("collect") || [];
    //2判断当前商品是否被收藏
    let isCollect = collect.some((v) => v.goods_id === this.GoodsInfo.goods_id);
    this.setData({
      goodsObj: {
        goods_name: res.goods_name,
        goods_price: res.goods_price,
        goods_introduce: res.goods_introduce.replace(/\.webp/g, ".jpg"),
        pics: res.pics,
      },
      isCollect,
    });
  },

  //点击轮播图，放大预览
  handlePreviewImage(e) {
    //console.log("预览");
    //1, 构造要与预览的图片数组
    const urls = this.GoodsInfo.pics.map((v) => v.pics_mid);
    const current = e.currentTarget.dataset.url;
    wx.previewImage({
      //2， 接收传递过来的图片url,避免点击第二张图片的时候还是出现第一张大图a
      current: current,
      urls: urls,
    });
  },

  //点击加入购物车
  handleCartAdd() {
    //1获取缓存中的购物车数组
    let cart = wx.getStorageSync("cart") || [];
    //2, 判断商品对象是否存在于数组中
    let index = cart.findIndex((v) => v.goods_id === this.GoodsInfo.goods_id);

    if (index === -1) {
      //3, 不存在 第一次添加
      this.GoodsInfo.num = 1;
      this.GoodsInfo.checked = true;
      cart.push(this.GoodsInfo);
      console.log(cart);
    } else {
      cart[index].num++;
      //4,已经存在购物车数据 num++
    }
    //5 把购物车重新添加回欢村中
    wx.setStorageSync("cart", cart);
    //6 弹窗提示
    wx.showToast({
      title: "加入成功",
      icon: "success",
      mask: true, //防止用户一直点很多下
    });
  },

  //点击商品收藏图标
  handleCollect() {
    let isCollect = false;
    //1， 获取缓存中的商品收藏数组
    let collect = wx.getStorageSync("collect") || [];
    //2， 判断数组中有没有该商品
    let index = collect.findIndex(
      (v) => v.goods_id === this.GoodsInfo.goods_id
    );
    //3, 当index!=-1 ，表示已经收藏过
    if (index != -1) {
      //已经收藏过,删除这个收藏
      collect.splice(index, 1);
      isCollect = false;
      wx.showToast({
        title: "取消收藏",
        icon: "success",
        mask: true,
      });
    } else {
      //没有收藏过， 添加到收藏
      collect.push(this.GoodsInfo);
      isCollect = true;
      wx.showToast({
        title: "收藏成功",
        icon: "success",
        mask: true,
      });
    }
    //4 把数组存入到缓存中
    wx.setStorageSync("collect", collect);
    //5 修改data中的属性 isCollect
    this.setData({
      isCollect,
    });
  },
});
